<?php

/**
 * 发票仓库
 * @author wangwx 2015-5-12
 */

namespace common\repositories\myhtsq;

use common\entities\ContractEntity;
use common\repositories\common\MyscrmContractSyncDeleteDataRepository;
use yii\db\Query;
use Exception;
use common\support\StringHelper;
use common\support\Helper;
use common\error\ErrorCode;
use common\repositories\BaseRepository;
use common\entities\myhtsq\InvoiceEntity;
use common\repositories\myhtsq\DocumentRepository;

class InvoiceRepository extends BaseRepository {

    /**
     * 构造函数
     * @param type $config
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 检查是否存在合同id发票
     * @param string $contractId 合同id
     * @return boolean
     */
    public static function isExistContractInvoice($contractId) {
        return InvoiceEntity::isExistContractInvoice($contractId);
    }

    /**
     * 检查是否存在对应的发票
     * @param string $invoiceId 合同id
     * @return boolean
     */
    public static function isExistInvoice($invoiceId) {
        return InvoiceEntity::isExistInvoice($invoiceId);
    }

    /**
     * 组建查找发票SQL
     * @param $where
     * @param $isMainInvoice
     * @param $invoiceStatus
     * @param $invoiceBeginDate
     * @param $invoiceEndDate
     * @param $searchKey
     * @return array
     */
    private function __buildGetInvoiceWhereSql($where, $isMainInvoice, $invoiceStatus, $invoiceBeginDate, $invoiceEndDate, $searchKey)
    {
        $params = [];

        if (isset($isMainInvoice) && intval($isMainInvoice) != -1) {
            $where = $where . ' and (invoice.is_main_invoice = :is_main_invoice)';
            $params[':is_main_invoice'] = $isMainInvoice;
        }

        if (isset($invoiceStatus) && intval($invoiceStatus) != -1) {
            if(intval($invoiceStatus) == 1){
                $where = $where . " and (invoice.contract_id is not null or invoice.contract_id <> '') ";
            }else{
                $where = $where . " and (invoice.contract_id is null or invoice.contract_id = '') ";
            }
        }

        if (isset($invoiceBeginDate) && !empty($invoiceBeginDate)) {

            $where = $where . ' and (invoice.invoice_date >= :invoice_begin_date)';
            $params[':invoice_begin_date'] = $invoiceBeginDate . ' 00:00:00';
        }

        if (isset($invoiceEndDate) && !empty($invoiceEndDate)) {
            $where = $where . ' and (invoice.invoice_date <= :invoice_end_date)';
            $params[':invoice_end_date'] = $invoiceEndDate . ' 23:59:59';
        }

        if (isset($searchKey) && !empty($searchKey)) {
            $where = $where . " and (invoice.invoice_no like CONCAT('%', :invoice_no, '%') or invoice.customer_name like CONCAT('%', :customer_name, '%') or contract.contract_code like CONCAT('%', :contract_code, '%'))";
            $params[':invoice_no'] = $searchKey;
            $params[':customer_name'] = $searchKey;
            $params[':contract_code'] = $searchKey;
        }

        return ['where' => $where, 'params' => $params];
    }

    /**
     * 发票管理模块：获取发票列表信息，支持分页
     * @param int $isMainInvoice 是否主发票
     * @param int $invoiceStatus 发票状态
     * @param int $invoiceBeginDate 开票开始日期
     * @param string $invoiceEndDate 开票结束日期
     * @param string $searchKey 查询关键字
     * @param int $pageIndex 页索引
     * @param int $pageSize 页大小
     * @return array PageResult
     */
    public function getInvoiceListByPage($isMainInvoice, $invoiceStatus, $invoiceBeginDate, $invoiceEndDate, $searchKey, $pageIndex = 1, $pageSize = 10 ,$invoice_mix_receipt =0) {

        if($invoice_mix_receipt){
            $where = 'invoice.contract_id IN (SELECT
			contract_id
		FROM
			myscrm_invoice
		WHERE
			is_receipt = 1)';
            $where = $where . ' and (invoice.is_receipt=0)';
        }else{
            $where = 'invoice.is_receipt=0 ';
        }

        $whereSql = $this->__buildGetInvoiceWhereSql($where, $isMainInvoice, $invoiceStatus, $invoiceBeginDate, $invoiceEndDate, $searchKey);

        $query = new Query();
        $queryFilter = $query->select("invoice.invoice_id,invoice.invoice_no,invoice.invoice_date,invoice.is_main_invoice,invoice.invoice_status,invoice.red_by_invoice_id,"
                        . "invoice.is_lose,invoice.is_red_invoice,invoice.is_reded_invoice,"
                        . "invoice.invoice_amount,invoice.receivables_amount, invoice.payment_amount,invoice.remark as invoiceSummary,"
                        . "invoice.customer_name, invoice.invoice_category, summary.summary_type, contract.customer_full_name, invoice.invoice_code, "
                        . "invoice.invoice_company_id,invoiceCompany.BUName as invoiceCompanyName, invoice.invoice_type, "
                        . "invoice.contract_id,contract.contract_code as contractCode,contract.company_id as contractCompanyId, "
                        . "contract.area_id as contractAreaId")
                ->from('myscrm_invoice invoice')
                ->leftJoin("myscrm_invoice_business_unit invoiceCompany", "invoice.invoice_company_id = invoiceCompany.BUGUID")
                ->leftJoin("myscrm_contract_manage contract", "invoice.contract_id = contract.contract_id")
                ->leftJoin("myscrm_invoice_summary summary", "invoice.invoice_id = summary.invoice_id")
                ->where($whereSql['where'], $whereSql['params']);

        $total = $queryFilter->count("1", ContractEntity::getDb());

        $skip = ($pageIndex - 1) * $pageSize;
        $result = $queryFilter
                ->offset($skip)
                ->limit($pageSize)
                ->orderBy(['invoice.created_on' => SORT_DESC])
                //exit($result->createCommand()->getRawSql());
                ->all(ContractEntity::getDb());

        if (0 === $total) {
            $items = [];
            return Helper::setPageResult($total, $items);
        } else {
            foreach ($result as $k => $v) {
                $invoiceDocuments = DocumentRepository::getDocumentListByBusinessId($v['invoice_id']);
                $result[$k]['invoiceDocuments'] = $invoiceDocuments;
                $result[$k]["contractCompanyName"] = ErpBusinessUnitRepository::getBunameByBuguid($v["contractCompanyId"]);
                $result[$k]["area_name"] = ErpBusinessUnitRepository::getBunameByBuguid($v["contractAreaId"]);
                $totalChildInvoiceAmount = 0;
                if ($v['is_main_invoice'] == 1) {
                    $childInvoices = self::getChildInvoiceInfo($v['invoice_id']);
                    if (isset($childInvoices) && count($childInvoices) > 0) {
                        foreach ($childInvoices as $k1 => $v1) {
                            if (isset($v1['invoice_amount']) && !empty($v1['invoice_amount'])) {
                                $totalChildInvoiceAmount += floatval($v1['invoice_amount']);
                            }
                        }
                    }
                }

                if($v['contract_id']){
                    $result[$k]['invoice_status'] = 1;
                }else{
                    $result[$k]['invoice_status'] = 0;
                }

                $result[$k]['totalChildInvoiceAmount'] = $totalChildInvoiceAmount;
            }
            return Helper::setPageResult($total, $result);
        }
    }

    /**
     * 获取发票/收据列表(导出)
     * @param $isMainInvoice
     * @param $invoiceStatus
     * @param $invoiceBeginDate
     * @param $invoiceEndDate
     * @param $searchKey
     * @param int $isReceipt 是否收据
     * @return array
     */
    public function getInvoiceListForExport($isMainInvoice, $invoiceStatus, $invoiceBeginDate, $invoiceEndDate, $searchKey, $isReceipt = 0)
    {
        $where = 'invoice.is_receipt=' . intval($isReceipt) . ' ';

        $whereSql = $this->__buildGetInvoiceWhereSql($where, $isMainInvoice, $invoiceStatus, $invoiceBeginDate, $invoiceEndDate, $searchKey);

        $query = new Query();
        $queryFilter = $query->select("invoice.invoice_id,invoice.invoice_no,invoice.invoice_date,invoice.is_main_invoice,invoice.invoice_status,invoice.red_by_invoice_id,"
            . "invoice.is_lose,invoice.is_red_invoice,invoice.is_reded_invoice,"
            . "invoice.invoice_amount,invoice.receivables_amount, invoice.payment_amount,invoice.remark as invoiceSummary,"
            . "invoice.customer_name, invoice.invoice_category, summary.summary_type, contract.customer_full_name, invoice.invoice_code, "
            . "invoice.invoice_company_id,invoiceCompany.BUName as invoiceCompanyName, invoice.invoice_type, "
            . "invoice.contract_id,contract.contract_code as contractCode,contract.company_id as contractCompanyId, "
            . "contract.area_id as contractAreaId,invoice.remark, invoice.proposer_id as invoiceProposerId")
            ->from('myscrm_invoice invoice')
            ->leftJoin("myscrm_invoice_business_unit invoiceCompany", "invoice.invoice_company_id = invoiceCompany.BUGUID")
            ->leftJoin("myscrm_contract_manage contract", "invoice.contract_id = contract.contract_id")
            ->leftJoin("myscrm_invoice_summary summary", "invoice.invoice_id = summary.invoice_id")
            ->where($whereSql['where'], $whereSql['params']);

        $result = $queryFilter
            ->orderBy(['invoice.created_on' => SORT_DESC])
            ->all(ContractEntity::getDb());

        foreach ($result as $k => $v) {
            $invoiceDocuments = DocumentRepository::getDocumentListByBusinessId($v['invoice_id']);
            $result[$k]['invoiceDocuments'] = $invoiceDocuments;

            $result[$k]["contractCompanyName"] = ErpBusinessUnitRepository::getBunameByBuguid($v["contractCompanyId"]);
            $result[$k]["area_name"] = ErpBusinessUnitRepository::getBunameByBuguid($v["contractAreaId"]);
            $result[$k]["UserName"]=ErpUserRepository::getUserNameByBuguid($v["invoiceProposerId"]);

            $totalChildInvoiceAmount = 0;
            if ($v['is_main_invoice'] == 1) {
                $childInvoices = self::getChildInvoiceInfo($v['invoice_id']);
                if (isset($childInvoices) && count($childInvoices) > 0) {
                    foreach ($childInvoices as $k1 => $v1) {
                        if (isset($v1['invoice_amount']) && !empty($v1['invoice_amount'])) {
                            $totalChildInvoiceAmount += floatval($v1['invoice_amount']);
                        }
                    }
                }
            }

            $result[$k]['totalChildInvoiceAmount'] = $totalChildInvoiceAmount;
        }

        return $result;
    }

    /**
     * 获取指定父级发票id下的所有子发票信息
     * @param string $mainInvoiceId 父级发票id
     * @return array
     */
    public static function getChildInvoiceInfo($mainInvoiceId) {
        $query = InvoiceEntity::find()
                ->where(['main_invoice_id' => $mainInvoiceId])
                ->asArray()
                ->all();
        return $query;
    }

    /**
     * 新增发票
     * @param \common\models\myhtsq\InvoiceModel $invoiceModel
     * @return boolean|string 失败返回false，成功返回发票Id
     */
    public static function addInvoice($invoiceModel) {
        try {
            $entity = new InvoiceEntity();
            $entity->isNewRecord = true;
            $entity->setAttributes($invoiceModel->attributes);
            if (!(isset($entity->invoice_id) && !empty($entity->invoice_id))) {
                $entity->invoice_id = StringHelper::uuid();
            }

            $result = $entity->save();
            if ($result === FALSE) {
                return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 依据金额获取收据
     */
    public static function getReceiptByContractId($ContractId,$InvoiceAmount) {
        $query = InvoiceEntity::find()
            ->where(['contract_id' => $ContractId,'is_receipt' => 1,'invoice_amount'=>$InvoiceAmount])
            ->one();
        return $query;
    }


    /**
     * @param $invoiceEntity \common\entities\myhtsq\InvoiceEntity
     * @return bool
     */
    public static function saveInvoice($invoiceEntity)
    {
        try {
            $invoiceEntity->save();
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL, $ex->getMessage());
        }

        return true;
    }

    /**
     * 修改发票
     * @param \common\models\myhtsq\InvoiceModel $invoiceModel
     * @return boolean|string 失败返回false，成功返回发票Id
     */
    public static function updateInvoice($invoiceModel) {
        try {
            $entity = InvoiceEntity::find()->where(['invoice_id' => $invoiceModel->invoice_id])->one();
            if (!isset($entity)) {
                return self::setAndReturn(ErrorCode::ERR_INVOICE_NOT_EXISTS);
            }

            $entity->setAttributes($invoiceModel->attributes);
            $result = $entity->update();
            if ($result === false) {
                return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->invoice_id;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 根据发票ID删除对应的发票信息
     * @param string $invoiceId 发票ID
     * @return boolean 返回true时表示删除成功，否则失败
     */
    public static function deleteInvoice($invoiceId)
    {
        /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
        $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

        $deleteResult = InvoiceEntity::deleteInvoice($invoiceId);

        if ($deleteResult !== true) {
            return self::setAndReturn(InvoiceEntity::getErrCode());
        }else{
            $contractSyncDeleteDataRepository->add('myscrm_invoice', 'invoice_id', $invoiceId);
        }

        return true;
    }

    /**
     * 根据发票ID设置当前发票成遗失状态
     * @param string $invoiceId 发票ID
     * @return boolean 返回true时表示设置成功，否则失败
     */
    public static function doLose($invoiceId) {
        $result = InvoiceEntity::doLose($invoiceId);
        if ($result !== true) {
            return self::setAndReturn(InvoiceEntity::getErrCode());
        }

        return true;
    }

    /**
     * 根据发票ID获取发票信息
     * @param string $invoiceId
     * @return array
     */
    public static function getInvoiceInfo($invoiceId) {
        $query = new Query();
        $query = $query->select("myscrm_invoice.*,myscrm_invoice_business_unit.BUName as invoice_company_name")
                ->from('myscrm_invoice')
                ->leftJoin('myscrm_invoice_business_unit', 'myscrm_invoice_business_unit.BUGUID = myscrm_invoice.invoice_company_id')
                ->where(['invoice_id' => $invoiceId])
                ->one(ContractEntity::getDb());

        //获取用户名
        if (!empty($query)) {
            $query["user_name"] = ErpUserRepository::getUserNameByBuguid($query["proposer_id"]);
        }

        return $query;
    }

    /**
     * 根据合同ID获取对应的发票信息
     * @param string $contractId
     * @return array
     */
    public static function getInvoiceListByContractId($contractId) {
        $query = InvoiceEntity::find()
                ->select('myscrm_invoice.*,invoiceCompany.BUName')
                ->leftJoin('myscrm_invoice_business_unit invoiceCompany', 'myscrm_invoice.invoice_company_id = invoiceCompany.BUGUID')
            ->where(['contract_id' => $contractId])
            ->andWhere(['is_main_invoice' => 0])
            ->asArray()
            ->all();
        //获取用户名
        if (!empty($query)) {
            foreach ($query as $k => $v) {
                $userName = "";
                $userCode = "";
                $user = ErpUserRepository::getUserById($v["proposer_id"]);
                if (!empty($user)) {
                    $userName = $user->UserName;
                    $userCode = $user->UserCode;
                }
                $query[$k]["UserName"] = $userName;
                $query[$k]["UserCode"] = $userCode;
            }
        }

        return $query;
    }

    /**
     * 特批界面获取发票select2控件下拉选项
     * @param string $keyword 搜索关键字
     * @param string $page 分页
     */
    public static function getInvoiceListForSepcialInvoiceSelect2($keyword, $limit = 10) {
        if (is_null($keyword) && empty($keyword)) {
            return [];
        }
        $query = new Query();
        return InvoiceEntity::find()
                        ->select('invoice_id,invoice_no as id,invoice_no as text')
                        ->where(['like', 'invoice_no', $keyword])
                        ->andWhere(['not exists', $query->select('invoice_no')->from('myscrm_special_approval_invoice')->where('myscrm_special_approval_invoice.invoice_no=myscrm_invoice.invoice_no')])
                        ->orderBy(['invoice_no' => SORT_ASC])
                        ->limit($limit)
                        ->asArray()
                        ->all();
    }

    /**
     * 获取可以作为父级发票的发票信息
     * @param string $keyword
     * @return array
     */
    public static function getParentInvoiceInfo($keyword) {
//        $sql = 'select invoice_id,invoice_code,invoice_no,invoice_amount,
//                       IFNULL((select sum(invoice_amount) from myscrm_invoice where main_invoice_id=parent.invoice_id),0) as childInvoiceAmount
//                from myscrm_invoice parent';
//        $query = InvoiceEntity::findBySql($sql)
//                ->where(['parent.is_main_invoice' => 1])
//                ->andWhere(['or', ['like', 'parent.invoice_no', $keyword], ['like', 'parent.invoice_code', $keyword]])
//                ->asArray()
//                ->all();

        $query = InvoiceEntity::find()
                ->where(['is_main_invoice' => 1])
                ->andWhere(['or', ['like', 'invoice_no', $keyword], ['like', 'invoice_code', $keyword]])
                ->asArray()
                ->all();

        if(isset($query) && count($query) > 0){
            foreach($query as $k=>$v){
                $child = self::getChildInvoiceInfo($v['main_invoice_id']);
                $childInvoiceAmount = 0;
                if(isset($child) && count($child) > 0){
                    if(isset($child['invoice_amount']) && !empty($child['invoice_amount'])){
                        $childInvoiceAmount += floatval($child['invoice_amount']);
                    }
                }

                $query[$k]['childInvoiceAmount'] = $childInvoiceAmount;
            }
        }

        return $query;
    }

    /**
     * 根据发票id获取发票的entity对象
     * @param string $invoiceId 发票ID
     * @return \common\entities\myhtsq\InvoiceEntity
     */
    public static function getInvoiceEntity($invoiceId) {
        $query = InvoiceEntity::find()
                ->where(['invoice_id' => $invoiceId])
                ->one();
        return $query;
    }

    /**
     * 获取所有可以被引用的发票信息
     * @param string $contractId
     * @param null $keyword
     * @return array
     */
    public static function getCanUseInvoiceInfo($contractId = null, $keyword = null)
    {
        $query = InvoiceEntity::find()
            ->select('myscrm_invoice.*,invoiceCompany.BUName,parentInvoice.invoice_code as parent_invoice_code,parentInvoice.invoice_no as parent_invoice_no')
            ->leftJoin('myscrm_invoice_business_unit invoiceCompany', 'myscrm_invoice.invoice_company_id = invoiceCompany.BUGUID')
            ->leftJoin('myscrm_invoice parentInvoice', 'myscrm_invoice.main_invoice_id = parentInvoice.invoice_id')
            ->where("myscrm_invoice.is_main_invoice = 0 and myscrm_invoice.is_lose = 0  "
                . "and (myscrm_invoice.contract_id is null or myscrm_invoice.contract_id = '') "
                . "and myscrm_invoice.receivables_amount = 0 and myscrm_invoice.invoice_amount<>0 ");

        if (isset($contractId) && !empty($contractId)) {
            if (isset($keyword) && !empty($keyword)) {
                $query = InvoiceEntity::find()
                    ->select('myscrm_invoice.*,invoiceCompany.BUName,parentInvoice.invoice_code as parent_invoice_code,parentInvoice.invoice_no as parent_invoice_no')
                    ->leftJoin('myscrm_invoice_business_unit invoiceCompany', 'myscrm_invoice.invoice_company_id = invoiceCompany.BUGUID')
                    ->leftJoin('myscrm_invoice parentInvoice', 'myscrm_invoice.main_invoice_id = parentInvoice.invoice_id')
                    ->where("myscrm_invoice.is_main_invoice = 0 and myscrm_invoice.is_lose = 0  "
                        . "and (myscrm_invoice.contract_id is null or myscrm_invoice.contract_id = '' or myscrm_invoice.contract_id = '" . $contractId . "') "
                        . "and (myscrm_invoice.customer_name like '%" . $keyword . "%' or myscrm_invoice.invoice_no like '%" . $keyword . "%') ");

            } else {
                $query->orWhere(['and',
                    ['myscrm_invoice.contract_id' => $contractId],
                    "myscrm_invoice.is_main_invoice = 0 and myscrm_invoice.is_lose = 0 "
                    . "and myscrm_invoice.receivables_amount = 0 and myscrm_invoice.invoice_amount<>0 "]);
            }
        }

        $result = $query
            ->asArray()
            ->all();

        if (isset($result) && count($result) > 0) {
            foreach ($result as $k => $v) {
                $invoiceSummary = InvoiceSummaryRepository::getInvoiceSummarysByInvoiceId($v['invoice_id']);
                $result[$k]['invoiceSummarys'] = $invoiceSummary;

                // UserName, UserCode
                $result[$k]["UserName"] = "";
                $result[$k]["UserCode"] = "";
                $user=ErpUserRepository::getUserById($result[$k]["proposer_id"]);
                if(!empty($user)){
                    $result[$k]["UserName"] = $user->UserName;
                    $result[$k]["UserCode"] = $user->UserCode;
                }

            }
        }

        return $result;
    }

    /**
     * 检查是否存在相同发票代码的发票
     * @param string $invoiceCode 发票代码
     * @param string $invoiceId 发票id
     * @return boolean true存在/false不存在
     */
    public static function exitSameInvoiceCode($invoiceCode, $invoiceId = null) {
        $query = InvoiceEntity::find()
                ->where(['invoice_Code' => $invoiceCode])
                ->andWhere('is_red_invoice = 0');

        if (isset($invoiceId) && !empty($invoiceId)) {
            $query->andWhere('invoice_id != :invoice_id', [':invoice_id' => $invoiceId]);
        }

        $result = $query->exists();

        return $result;
    }

    /**
     * 检查是否存在相同发票编号的发票
     * @param string $invoiceNo 发票编号
     * @param string $invoiceId 发票id
     * @return boolean true存在/false不存在
     */
    public static function exitSameInvoiceNo($invoiceNo, $invoiceId = null) {
        $query = InvoiceEntity::find()
                ->where(['invoice_no' => $invoiceNo]);

        if (isset($invoiceId) && !empty($invoiceId)) {
            $query->andWhere('invoice_id != :invoice_id', [':invoice_id' => $invoiceId]);
        }

        $result = $query->exists();

        return $result;
    }

    /**
     * 检查是否存在指定客户的发票且未关联合同
     * @param $custName
     * @return bool
     */
    public static function existInvoiceNotRelContract($custName){
        $query = InvoiceEntity::find()
        ->where(['customer_name'=>$custName])->andWhere(['or',['contract_id'=>null], ['contract_id'=>'']]);

        return $query->exists();
    }

    /**
     * 获取过期未全部回款的发票
     * @param $expiredDate 过期日期
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getExpiredInvoices($expiredDate){
        $query = InvoiceEntity::find()
            ->where("contract_id is not null and contract_id<>'' and receivables_amount<>payment_amount")
            ->andWhere(['is_red_invoice'=>0,'is_lose'=>0,'invoice_date'=>$expiredDate])
            ->asArray()
            ->all();
        return $query;
    }

    /**
     * @param $invoiceId
     * @return mixed
     */
    public static function getInvoiceInfoById ($invoiceId) {
        $result = InvoiceEntity::find()
            ->select('myscrm_invoice.*,invoiceCompany.BUName,parentInvoice.invoice_code as parent_invoice_code,parentInvoice.invoice_no as parent_invoice_no')
            ->leftJoin('myscrm_invoice_business_unit invoiceCompany', 'myscrm_invoice.invoice_company_id = invoiceCompany.BUGUID')
            ->leftJoin('myscrm_invoice parentInvoice', 'myscrm_invoice.main_invoice_id = parentInvoice.invoice_id')
            ->where("myscrm_invoice.invoice_id='".$invoiceId."'")->asArray()->all();

        if (isset($result) && count($result) > 0) {
            foreach ($result as $k => $v) {
                // UserName, UserCode
                $result[$k]["UserName"] = "";
                $result[$k]["UserCode"] = "";
                $user = ErpUserRepository::getUserById($result[$k]["proposer_id"]);
                if (!empty($user)) {
                    $result[$k]["UserName"] = $user->UserName;
                    $result[$k]["UserCode"] = $user->UserCode;
                }
            }
        }
        return $result;
    }
 
    public static function checkInvoiceExists($contractId)
    {
        return InvoiceEntity::find()->where(["contract_id"=>$contractId])->exists();
    }

    /**
     * 获取合同开票金额
     * @param array $contractIds
     * @param int $is_receipt 是否是收据 0=>否 1->是
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getAllBillingAmountSumByContractIds($contractIds, $is_receipt = 0)
    {
        return InvoiceEntity::find()
            ->select('sum(invoice_amount) as billing_amount, contract_id')
            ->where([
                'contract_id' => $contractIds
                ,'is_receipt' => $is_receipt
            ])
            ->groupBy('contract_id')
            ->asArray()
            ->all();
    }

    /**
     * @param $contractId
     * @param int $isReceipt
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getInvoicesByContractId($contractId,$isReceipt = 0)
    {
        return InvoiceEntity::find()
            ->select('invoice_amount, contract_id')
            ->where([
                'contract_id' => $contractId,
                'is_receipt' => $isReceipt
            ])
            ->asArray()
            ->all();
    }

}
